package Socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/*
聊天室的客户端

为了能够收发信息
 */
public class Client3 {
    private Socket socket;

    public Client3() {
        try {
            System.out.println("客户端开始运行");
            socket = new Socket("172.86.0.54", 8088);
            System.out.println("已经连接");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {

            //发送消息给服务器
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);

            //接收信息
            InputStream in= socket.getInputStream();
            InputStreamReader isr=new InputStreamReader(in, StandardCharsets.UTF_8);
            BufferedReader br=new BufferedReader(isr);
            Scanner sc = new Scanner(System.in);


            Thread t1=new Thread("Send message"){
                @Override
                public void run() {
                    System.out.println("开始发送信息");
                    while (true) {
                        //发送
                        String line;
                        line = sc.nextLine();
                        if ("exit".equals(line)) {
                            break;
                        }
                        pw.println(line);
                    }
                }
            };
            Thread t2=new Thread("Receive message"){
                @Override
                public void run() {
                    System.out.println("开始接收消息");
                    //接收消息
                    try {
                        while (br.readLine()!=null){
                            System.out.println("The server said: "+br.readLine());
                        }
                    } catch (IOException e) {

                    }
                }
            };
            t1.start();
            t2.start();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();  //与服务端断开
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client3 client = new Client3();
        client.start();
    }
}
